package com.suncnpap.journal.controller;

import com.suncnpap.journal.model.BorrowJournal;
import com.suncnpap.journal.model.BorrowJournalRecord;
import com.suncnpap.journal.model.Journal;
import com.suncnpap.journal.model.JournalRegistration;
import com.suncnpap.journal.model.ReturnJournal;
import com.suncnpap.journal.service.BorrowJournalRecordService;
import com.suncnpap.journal.service.BorrowJournalService;
import com.suncnpap.journal.service.JournalRegistrationService;
import com.suncnpap.journal.service.JournalService;
import com.suncnpap.journal.service.JournalTypeService;
import com.suncnpap.journal.service.ReturnJournalService;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.reader.model.ReaderType;
import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.reader.service.ReaderTypeService;
import com.suncnpap.statistics.annotation.LogType;
import com.suncnpap.statistics.annotation.SysLog;
import com.suncnpap.system.model.Config;
import com.suncnpap.system.model.School;
import com.suncnpap.system.service.ConfigService;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.util.beanutil.BeanUtil;
import com.app.util.common.Constants;
import com.app.util.common.EasyuiGrid;
import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.UuidUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.base.common.ParamModel;
import com.suncnpap.base.controller.BaseController;
import com.suncnpap.datamanage.common.ExportExcelUtils;

/** 
 * 说明：期刊登记Controller
 */
@Controller
@RequestMapping(value="/journal/journalRegistration")
public class JournalRegistrationController extends BaseController {
	
	//private static final Logger log = Logger.getLogger(JournalRegistrationController.class);
	
	@Autowired
	JournalRegistrationService journalRegistrationService;
	
	@Autowired
	JournalService journalService;
	
	@Autowired
	ConfigService configService;
	/**
	 * 列表页面数据处理，包括查询
	 * @param page
	 * @param response
	 */
	@RequestMapping(value="/list" )
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		
		if (result.getCode()==0) {

			Page page = this.setPage();
			
			page.removeQueryAnd("strSchoolId");
			page.addQueryAnd("r.strSchoolId", GlobaUser.getStrSchoolId(request.getHeader("token")));
			
			String strJournalId = this.getParameter("strJournalId", "");
			if(!strJournalId.equals("")){
				page.addQueryAnd("r.strJournalId", strJournalId);
			}
//			page.put("strJournalId", strJournalId);
			
//			Page journalPage = new Page();
			//邮发代号
			String strPostcode = this.getParameter("strPostcode", "");
			if(!strPostcode.equals("")){
				page.addQueryAnd("j.strPostcode", strPostcode);
//				page.put("strPostcode", strPostcode);
			}
			//统一刊号
			String strUnifiedIssue = this.getParameter("strUnifiedIssue", "");
			if(!strUnifiedIssue.equals("")){
				page.addQueryAnd("j.strUnifiedIssue", strUnifiedIssue);
//				page.put("strUnifiedIssue", strUnifiedIssue);
			}
			//期刊名
			String strJournalTitle = this.getParameter("strJournalTitle", "");
			if(!strJournalTitle.equals("")){
				page.addQueryAnd("j.strJournalTitle", strJournalTitle);
//				page.put("strJournalTitle", strJournalTitle);
			}
			//期号
			String strIssue = this.getParameter("strIssue", "");
			if(!strIssue.equals("")){
				page.addQueryAnd("j.strIssue", strIssue);
//				page.put("strIssue", strIssue);
			}
			//分类号
			String strClassificationNumber = this.getParameter("strClassificationNumber", "");
			if(!strClassificationNumber.equals("")){
				page.addQueryAnd("j.strClassificationNumber", strClassificationNumber);
//				page.put("strClassificationNumber", strClassificationNumber);
			}
			//开始条码
			String strStartBarcodeNumber = this.getParameter("strStartBarcodeNumber", "");
			if(!strStartBarcodeNumber.equals("")){
				page.addQueryAnd("r.strBarcodeNumber", QueryType.markGTEQ, strStartBarcodeNumber);
//				page.put("strStartBarcodeNumber", strStartBarcodeNumber);
			}
			//结束条码
			String strEndBarcodeNumber = this.getParameter("strEndBarcodeNumber", "");
			if(!strEndBarcodeNumber.equals("")){
				page.addQueryAnd("r.strBarcodeNumber", QueryType.markLTEQ, strEndBarcodeNumber);
//				page.put("strEndBarcodeNumber", strEndBarcodeNumber);
			}
			
			page = journalRegistrationService.list(page);
			
			String isExp = this.getParameter("isExp", "");
			if(isExp.equals("1")){
				List<JournalRegistration> libraryList = page.getDataList();
				String header = "序号,期号,期刊名,年号,统一刊号,邮发代号,出版单位,ISSN,分类号"
						+ "类型,期刊条码,价格,书屋位置,入库时间,操作员";
				
				String tableStr = "xh,strIssue,strJournalTitle,strYear,strUnifiedIssue,strPostcode,strEditorialDepartment,strJournalIssue,strClassificationNumber,"
						+ "strType,strBarcodeNumber,fPrice,strCollectionLocation,dtCreatDate,strCreatName";
				
				ExportExcelUtils util = new ExportExcelUtils();
				String path = "upload/exp/";
				String fileName = UuidUtil.get32UUID()+".xls";
				util.exportExcel("期刊登记", ObjUtil.strToList(header), ObjUtil.strToList(tableStr),libraryList, path, fileName);
				
				result.put("path", path);
				result.put("fileName", fileName);
			}else{
				result = this.returnPage(result, page);
			}
		}
		
		ResponseUtil.writeJson(result, response);

	}
	
	/**
	 * 添加处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@SysLog(type=LogType.JOURNALCATALOGUING)
	public void add(@RequestBody JournalRegistration obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				
				Config config = configService.findBySchoolId(GlobaUser.getStrSchoolId(request.getHeader("token")));
				int intLength = config.getIntEffectiveLength();
				intLength = intLength==0?6:intLength;
				
				String strBookBarcode = obj.getStrBarcodeNumber();
				int barcodeNumber = Integer.valueOf(strBookBarcode);
				
				if(strBookBarcode.length()>intLength){
					intLength = strBookBarcode.length();
				}
				
				String strRepeatBookBarcode = "";
				Integer intDuplicate = obj.getIntDuplicate();
				intDuplicate = intDuplicate==null ?1:intDuplicate;
				if(intDuplicate != null && intDuplicate>0){
					for(int i=0;i<intDuplicate;i++){
						
						String tempCode = barcodeNumber +"";
						int codeLength = tempCode.length();
						if(codeLength<intLength){
							for(int j=0;j<intLength-codeLength;j++){
								tempCode = "0"+tempCode;
							}
						}
//						String tempCode = (barcodeNumber+"").length()<6?g1.format(barcodeNumber++):(barcodeNumber++ + "");
						JournalRegistration journalRegistration = journalRegistrationService.findByBarcode(tempCode, strSchoolId);
						if(journalRegistration==null){
							super.init(obj);
							obj.setStrBarcodeNumber(tempCode);
							journalRegistrationService.add(obj);
						}else{
							strRepeatBookBarcode += strRepeatBookBarcode.equals("")?tempCode:(","+tempCode);
						}
						barcodeNumber++;
					}
				}
				
				String tempCode = barcodeNumber +"";
				int codeLength = tempCode.length();
				if(codeLength<intLength){
					for(int j=0;j<intLength-codeLength;j++){
						tempCode = "0"+tempCode;
					}
				}
				result.put("strBarcodeNumber", barcodeNumber);
				if(!strRepeatBookBarcode.equals("")){
					result.setCode(1);
					result.setMessage("已存在："+strRepeatBookBarcode+"期刊条码，请重新分配条码");
				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public void update(@RequestBody JournalRegistration obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				journalRegistrationService.update(obj);
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	
	@RequestMapping(value="/view")
	public void view(@RequestBody ParamModel paramModel,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = paramModel.getStrId();
				JournalRegistration obj = journalRegistrationService.findById(strId);
				result.put("obj", obj);
				
				Journal journal = journalService.findById(obj.getStrJournalId());
				result.put("journal", journal);
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 删除处理
	 * @param strId
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public void delete(@RequestBody ParamModel paramModel,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = paramModel.getStrId();
				if(strId != null && !strId.equals("")){
					journalRegistrationService.deleteMore(strId.split(","));
				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 添加处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/merge",method=RequestMethod.POST)
	public void merge(@RequestBody JournalRegistration obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = obj.getStrId();
				if(strId != null && !strId.equals("")){
					journalRegistrationService.deleteMore(strId.split(","));
				}
				super.init(obj);
				journalRegistrationService.add(obj);
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
}
